﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using AddIn.EA.Util.AddInActions;
using AddIn.EA.Core.Common;
using Microsoft.Win32;

namespace AddIn.EA.Util
{
    class Program
    {
        private const string FolderFW20 = "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727";
        public Program() { }

        static void Main(string[] args)
        {
            Program program = new Program();

            if (args.Length > 0 && args[0].Substring(0, 1) == "/")
            {
                switch (args[0].ToLower())
                {
                    case "/i":
                        if (args.Length > 1)
                            program.Install(args[1]);
                        else
                            Console.WriteLine("It wasn't sent the full path of the assembly file.");
                        break;
                    case "/u":
                        if (args.Length > 1)
                            program.Uninstall(args[1]);
                        else
                            Console.WriteLine("It wasn't sent the assembly file name.");
                        break;
                    case "/load":
                        program.Load();
                        break;
                    case "/unload":
                        program.Unload();
                        break;
                    case "/?":
                    case "/h":
                    case "/help":
                        program.Help();
                        break;
                    default:
                        Console.WriteLine("Invalid parameters!");
                        break;
                }
            }
            else
                program.Help();

            
        }

        public void Install(string assemblyFullPath)
        {
            AddInInstall addIn = new AddInInstall();
            addIn.OnSendMessage += new AddInInstall.AddInInstallMessage(addIn_OnSendMessage);
            addIn.Install(assemblyFullPath);
        }

        void addIn_OnSendMessage(object sender, AddInInstall.AddInInstallMessageEventArgs e)
        {
            Console.WriteLine(e.Message);
        }

        public void Uninstall(string assemblyName)
        {
            AddInInstall addIn = new AddInInstall();
            addIn.OnSendMessage += new AddInInstall.AddInInstallMessage(addIn_OnSendMessage);
            addIn.Uninstall(assemblyName);
        }

        public void Load()
        {
            Console.WriteLine(string.Format("{0}\n\n", Properties.Resources.AddInArchitectureHeader));
            Console.WriteLine("LOAD\n\n");

            Console.WriteLine("The process to load the Add-In for Architecture Team was started. Please Wait. . .");

            RegistryKey subKey = Registry.LocalMachine.CreateSubKey(AddInRegistryResources.SubKey);
            subKey.SetValue(AddInRegistryResources.BaseDirectoryKey, AppDomain.CurrentDomain.BaseDirectory);
            subKey.SetValue(AddInRegistryResources.MenuKey, "Menu");
            subKey.SetValue(AddInRegistryResources.MenuNameKey, "Architecture");
            subKey.SetValue(AddInRegistryResources.SchemaKey, "Schema\\AddInArchitecture.xsd");

            RegistryKey frameworkKey = Registry.CurrentUser.CreateSubKey(AddInRegistryResources.FrameworkKey);
            frameworkKey.SetValue(null, AppDomain.CurrentDomain.BaseDirectory);

            string filePath = Path.Combine(AddInRegistryResources.GetApplicationFolder(), "AddIn.EA.Core.dll");
            if (!File.Exists(filePath))
            {
                string baseFolderPath = AddInRegistryResources.GetApplicationFolder();
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddIn.EA.Core.dll"), Path.Combine(baseFolderPath, "AddIn.EA.Core.dll"));
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddIn.EA.Framework.dll"), Path.Combine(baseFolderPath, "AddIn.EA.Framework.dll"));
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EA_Application.dll"), Path.Combine(baseFolderPath, "EA_Application.dll"));
            }

            Process loadProcess = new Process();
            loadProcess.StartInfo.CreateNoWindow = false;
            loadProcess.StartInfo.FileName = Path.Combine(FolderFW20, "regsvcs.exe");
            loadProcess.StartInfo.Arguments = string.Concat("\"", filePath, "\"");
            loadProcess.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            loadProcess.ErrorDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            if (loadProcess.Start())
                loadProcess.WaitForExit();

            RegistryKey subKeyEA = Registry.CurrentUser.CreateSubKey(AddInRegistryResources.AddInEAKey);
            subKeyEA.SetValue(null, "AddIn.EA.Core.ProxyClient");

            Console.WriteLine("Add-In for Architecture was loaded successfully");
        }

        public void Unload()
        {
            Console.WriteLine(string.Format("\n{0}\n\n", Properties.Resources.AddInArchitectureHeader));
            Console.WriteLine("UNLOAD\n\n");

            Console.WriteLine("The process to unload the Add-In for Architecture Team was started. Please Wait. . .");

            string filePath = Path.Combine(AddInRegistryResources.GetApplicationFolder(), "AddIn.EA.Core.dll");

            Process unloadProcess = new Process();
            unloadProcess.StartInfo.CreateNoWindow = false;
            unloadProcess.StartInfo.FileName = Path.Combine(FolderFW20, "regsvcs.exe");
            unloadProcess.StartInfo.Arguments = string.Format("/u \"{0}\"", filePath);
            unloadProcess.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            unloadProcess.ErrorDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            if(unloadProcess.Start())
                unloadProcess.WaitForExit();

            Registry.CurrentUser.DeleteSubKeyTree("Software\\Sparx Systems\\EAAddins");
            Registry.CurrentUser.DeleteSubKeyTree(AddInRegistryResources.FrameworkKey);

            Directory.Delete(AddInRegistryResources.GetApplicationFolder(), true);

            Registry.LocalMachine.DeleteSubKeyTree(AddInRegistryResources.SubKey);

            Console.WriteLine("Add-In for Architecture was unloaded successfully");
        }

        void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine(e.Data);
        }

        public void Help()
        {
            Console.WriteLine(string.Format("\n{0}\n\n", Properties.Resources.AddInArchitectureHeader));
            Console.WriteLine(Properties.Resources.AddInArchitectureHelp);
        }
    }
}

